package com.lin.benchmade.timer;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lin.benchmade.Benchmade;
import com.lin.benchmade.pinyin.PinYinConverter;
import com.lin.benchmade.ts.JChineseConvertor;

public class BenchmadeListener implements ServletContextListener {

	private final Logger LOG = LoggerFactory.getLogger(BenchmadeListener.class);

	private ScheduledExecutorService rebuildTimer;
	private Benchmade it;
	private JChineseConvertor chineseConvertor;

	@Override
	public void contextInitialized(ServletContextEvent arg0) {

		it = Benchmade.getInstance();
		/*Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 3);
		calendar.set(Calendar.MINUTE, 0);
		Date rebuildTime = calendar.getTime();*/
		rebuildTimer = Executors.newScheduledThreadPool(1);
		rebuildTimer.scheduleAtFixedRate(new BenchmadeTimer(), 1000 * 60 * 30L, 30, TimeUnit.MINUTES);
		rebuildTimer.shutdown();

		chineseConvertor = JChineseConvertor.getInstance();
		LOG.info("*** Engine initialized successful!");
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	class BenchmadeTimer implements Runnable {
		@Override
		public void run() {
			InportTimer itimer;
			try {
				itimer = new InportTimer();
				LOG.info("start rebuilding .....");
				try {
					Map<String, Integer> map = itimer.build();
					char[] simplified_CN_cArr;
					char[] traditionalCN_cArr;
					String[] pinyinArray;
					for (Entry<String, Integer> entry : map.entrySet()) {
						simplified_CN_cArr = chineseConvertor.t2s(entry.getKey()).toCharArray();
						traditionalCN_cArr = new char[simplified_CN_cArr.length];
						pinyinArray = PinYinConverter.INSTANCE.encodeFillAndToPinyin(simplified_CN_cArr, traditionalCN_cArr);
						it.append(traditionalCN_cArr, entry.getValue(), pinyinArray);
					}
					map = null;
					it.rebuild();
				} catch (Exception e) {
					e.printStackTrace();
				}
				LOG.info("success rebuilding .....");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
}
